﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using Reviewer.Entities.Services;
using Reviewer.Business;
using Reviewer.Entities;
using System.Globalization;
using System.IO;

/// <summary>
/// Summary description for UrlUtillity
/// </summary>
public static class UrlUtillity
{
    public static string GetReviewUri(Review review)
    {
        Format format = null;
        Game game = null;
        using (IGameService gameService = ServiceFactory.GameService)
        using (IMetadataService<Format> formatService = ServiceFactory.GetMetadataService<Format>())
        {
            game = gameService.GetBy(review.GameId);
            if (game != null && game.Format > 0)
            {
                format = formatService.GetAll().FirstOrDefault(t => t.Id.Equals(game.Format));
            }
        }
        return GetReviewUri(format == null ? String.Empty : format.Name, game.Title);
    }

    public static string GetReviewUri(string gameFormatName, string gameTitle)
    {
        return VirtualPathUtility.ToAbsolute("~/anmeldelse/" + (String.IsNullOrEmpty(gameFormatName) ? "" : NormalizeString(gameFormatName) + "/") + NormalizeString(gameTitle) + ".aspx");
    }

    public static string GetNewsUri(News news)
    {
        return GetNewsUri(news.Title);
    }

    public static string GetNewsUri(string newsTitle)
    {
        return VirtualPathUtility.ToAbsolute("~/nyhed/" + NormalizeString(newsTitle) + ".aspx");
    }

    public static string GetGameUri(Game game)
    {
        Format item = null;
        using (IMetadataService<Format> service = ServiceFactory.GetMetadataService<Format>())
        {
            item = service.GetAll().FirstOrDefault(t => t.Id.Equals(game.Format));
        }

        return GetGameUri(game.Title, item == null ? "" : NormalizeString(item.Name));
    }

    public static string GetGameUri(string gameTitle, string gameFormatName)
    {
        return VirtualPathUtility.ToAbsolute("~/spil/" + (String.IsNullOrEmpty(gameFormatName) ? "" : NormalizeString(gameFormatName) + "/") + NormalizeString(gameTitle) + ".aspx");
    }

    public static string GetGameScreenshotUri(GameScreenshot screenshot)
    {
        return GetGameScreenshotUri(screenshot.Id, screenshot.GameId);
    }

    public static string GetGameScreenshotUri(int screenshotId, Guid gameId)
    {
        return VirtualPathUtility.ToAbsolute("~/screenshot.aspx") + "?PicID=" + screenshotId.ToString() + "&SpilID=" + gameId.ToString();
    }

    public static string GetGamescreenshotImageUri(GameScreenshot screenshot)
    {
        return GetGamescreenshotImageUri(screenshot.FileName);
    }

    public static string GetGameCoverUri(Game game)
    {
        return GetGameCoverUri(game.GameId, game.Format);
    }

    public static string GetGameCoverUri(Guid gameGuid, int formatId)
    {
        string coverFilename = String.Format(CultureInfo.InvariantCulture, "{0}/{1}_{2}."
                   , VirtualPathUtility.ToAbsolute("~/covers")
                   , gameGuid.ToString()
                   , formatId);

        if (File.Exists(HttpContext.Current.Server.MapPath(coverFilename + "png")))
        {
            return coverFilename + "png";
        }
        else if (File.Exists(HttpContext.Current.Server.MapPath(coverFilename + "jpg")))
        {
            return coverFilename + "jpg";
        }
        else
        {
            return "/App_Themes/RV2/Images/cover" + formatId.ToString() + ".jpg";
        }
    }

    public static string GetGamescreenshotImageUri(string fileName)
    {
        return VirtualPathUtility.ToAbsolute("~/screenshots/" + fileName);
    }

    public static string GetGameVideoUri(GameVideo gameVideo)
    {
        using (IGameService gameService = ServiceFactory.GameService)
        {
            Game currentGame = gameService.GetBy(gameVideo.GameId).FirstOrDefault();
            return GetGameVideoUri(gameVideo, currentGame);
        }
    }

    public static string GetGameVideoUri(GameVideo gameVideo, Game game)
    {
        return VirtualPathUtility.ToAbsolute("~/video/" + NormalizeString(game.Title) + "/Video-" + gameVideo.Id + ".aspx");
    }

    public static string NormalizeString(string unnormalized)
    {
        Regex removeChars = null;
        if (String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["UriReplaceChars"]))
        {
            removeChars = new Regex(@"[^0-9A-Za-zÆæØøÅå\-]", RegexOptions.Compiled);
        }
        else
        {
            removeChars = new Regex(System.Configuration.ConfigurationManager.AppSettings["UriReplaceChars"], RegexOptions.Compiled);
        }

        Regex andExpr = new Regex("&", RegexOptions.Compiled);
        Regex atExpr = new Regex("@", RegexOptions.Compiled);
        Regex dashExpr = new Regex(@"\?'\|\=\:;\.\,\%", RegexOptions.Compiled);
        Regex spaceExpr = new Regex(" ", RegexOptions.Compiled);
        Regex doubleDashExpr = new Regex("--", RegexOptions.Compiled);

        string returnValue = andExpr.Replace(unnormalized, " and ");
        returnValue = atExpr.Replace(returnValue, " at ");
        returnValue = returnValue.Replace(":", "-").Replace(";", "-").Replace("?", "-").Replace("|", "-").Replace(".", "-").Replace(",", "-").Replace("%", "-");
        returnValue = dashExpr.Replace(returnValue, "-");
        returnValue = spaceExpr.Replace(returnValue, "-");

        returnValue = removeChars.Replace(returnValue, "");

        returnValue = doubleDashExpr.Replace(returnValue, "-");
        returnValue = doubleDashExpr.Replace(returnValue, "-");

        if (returnValue.EndsWith("-"))
        {
            returnValue = returnValue.Substring(0, returnValue.Length - 1);
        }

        return returnValue;
    }
}
